package com.yjd.bi.etl.user.service;

import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.yjd.bi.etl.comm.BaseService;
import com.yjd.bi.etl.sql.UserSqlConstants;
import com.yjd.bi.report.model.BiDatabaseInfoModel;
import com.yjd.bi.report.util.BiUtil;
import com.yjd.comm.util.DateUtil;
import com.yjd.comm.util.FrameUtil;

@Component("userRealTimeStatisticService")
public class UserRealTimeStatisticService extends BaseService {

	private static final long FIRSTDAY = 1387641600L;
	private static final int  DAYOFHALFHOUR = 1800;
	private static final int  DAYOFHOUR = 3600;

	public void statisticEveryHalfHourData() throws Exception {

		BiDatabaseInfoModel model = this.getBiDatabaseInfoModel();
		JdbcTemplate jt = BiUtil.getJdbcTemplate(model);
		Long beginTime = 0l; // 初始化开始时间
		Map<String, Object> res = jt
				.queryForMap(UserSqlConstants.GET_MAX_USERSTATISTICS_REALTIME_DATE);
		String maxDate = String.valueOf(res.get("maxDate"));
		if (res.get("maxDate") != null) {
			beginTime = DateUtil.dateStringToTimestamp(maxDate,
					DateUtil.PATTERN_yyyyMMddHHmmss);
		} else {
			beginTime = FIRSTDAY;
		}
		
		while (beginTime+DAYOFHOUR <= FrameUtil.getTime()) {
			// 每半小时统计充值用户和投资用户数
			beginTime += DAYOFHALFHOUR;
			statisticHalfHourData(beginTime, jt);
		}
	}

	/**
	 * 统计某半小时的用户数据
	 */
	private void statisticHalfHourData(long maxDate, JdbcTemplate jt)
			throws Exception {

		long beginDate = maxDate;
		long endDate = maxDate + DAYOFHALFHOUR-1;//没半小时统计
		Long staticsDate = Long.parseLong(DateUtil.timestampToDateString(
				beginDate, DateUtil.PATTERN_yyyyMMddHHmmss));
		// 充值用户数
		int rechargeCount = jt.queryForInt(UserSqlConstants.RECHARGECOUNTSQL,beginDate, endDate);

		// 投资用户数
		int investCount = jt.queryForObject(UserSqlConstants.INVESTCOUNTSQL,new Object[] {beginDate, endDate, beginDate, endDate, beginDate, endDate},Integer.class);

		try{
			jt.update(UserSqlConstants.USERSTATISTIC_REAL_TIME_INSERTSQL,staticsDate, rechargeCount, investCount);
		}catch(Exception e){
			logger.info("批量处理插入失败，处理sql:"+UserSqlConstants.USERSTATISTIC_REAL_TIME_INSERTSQL+"处理数据:"+staticsDate+"错误信息:"+e);
		}

	}
}
